package pt.ipl.isel.deetc.leic.pdm.g12.yamba;

import java.util.Timer;
import java.util.TimerTask;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.TextView;

public class TimelineActivity extends BaseActivity implements OnItemClickListener  {
	private ListView listTimeline;
	private SimpleCursorAdapter adapter = null;
	private Timer autoUpdate;
	private Cursor cursor;
	
	private String[] from = {StatusContract.DATE_CREATED, StatusContract.USER, StatusContract.STATUS};
	private int[] to = {R.id.statusTime, R.id.statusUser, R.id.statusText};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.timeline);

		listTimeline = (ListView)findViewById(R.id.listTimeline);
		listTimeline.setOnItemClickListener(this);
		
		updateTimeline();
		
		Log.d(YambaPdmApp.TAG, "onCreate Timeline");
	}
	
	@Override
	protected void onResume() {		
		super.onResume();
		Boolean timelineUpdateIntervalCheck = yamba.getPreferences().getBoolean("timelineUpdateIntervalCheck", true);
		
		if(timelineUpdateIntervalCheck) {
			String timelineUpdateInterval = yamba.getPreferences().getString("timelineUpdateInterval", "5000");
			autoUpdate = new Timer();
			autoUpdate.schedule(new TimerTask() {
				@Override
				public void run() {
					runOnUiThread(new Runnable() {
						public void run() {
							updateTimeline();
							Log.d(YambaPdmApp.TAG, "autoUpdate");
						}
					});
				}
			}, 0, Integer.parseInt(timelineUpdateInterval) * 1000);
		}
		else
			updateTimeline();
	}
	
	@Override
	public void onPause() {
		super.onPause();
		autoUpdate.cancel();
		if (adapter != null){
	    	  adapter.getCursor().close();
	    	  adapter = null;
	    }		
	}
	
	@Override
	protected void onStop() {
		super.onStop();

		if (adapter != null){
			adapter.getCursor().close();
			adapter = null;
		}
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.removeItem(R.id.timeline);		
		return super.onPrepareOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {		
		switch(item.getItemId()){
		case R.id.refreshTimeline:			
			updateTimeline();			
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	protected void updateTimeline() {
		Boolean timelineUpdateIntervalCheck = yamba.getPreferences().getBoolean("timelineUpdateIntervalCheck", true);
		if(!timelineUpdateIntervalCheck){
			stopManagingCursor(cursor);
			yamba.updateStatusList();
		}			

		Cursor cursor = getContentResolver().query(StatusContract.CONTENT_URI, null, null, null, StatusContract.DATE_CREATED + " DESC");
    	startManagingCursor(cursor);
        adapter = new SimpleCursorAdapter(getBaseContext(), R.layout.timeline_row, cursor, from, to);
        adapter.setViewBinder(VIEW_BINDER);		    
		listTimeline.setAdapter(adapter);
	}
	
	public void onItemClick(AdapterView<?> a, View view, int pos, long id) {
		
		Cursor o = (Cursor)adapter.getItem(pos);
				
		Intent intent = new Intent(this, DetailActivity.class);
		intent.putExtra("id", o.getLong(0));
		intent.putExtra("user", o.getString(1));
		intent.putExtra("time", DateUtils.getRelativeTimeSpanString(o.getLong(2)));
		intent.putExtra("status", o.getString(3));
		
		startActivity(intent);
	}
	
	private ViewBinder VIEW_BINDER = new ViewBinder() 
	{ 
		public boolean setViewValue(View view, Cursor cursor, int columnIndex) 
		{ 				    
	    	if(view.getId() == R.id.statusTime) 
	    	{	    		
	    		long time = cursor.getLong(columnIndex); 	    	    
	    	    ((TextView)view).setText(DateUtils.getRelativeTimeSpanString(time)); 
	    		return true; 
	    	}
	    	if(view.getId() == R.id.statusText) 
	    	{	    		    		
	    		int maxMsgDim = Integer.parseInt(yamba.getPreferences().getString("maxTlMsgDim", "24"));
	    		String status = cursor.getString(columnIndex);
	    		((TextView)view).setText(status.length() > maxMsgDim ? status.substring(0, maxMsgDim + 1) : status);	
	    	}	    	
	    	
	    	return false;
	    }
	};		
}
